<template>
  <div class="post-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>帖子管理</h1>
      <p class="subtitle">查看和管理所有帖子内容</p>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="filter-card">
      <div class="filter-section">
        <div class="search-bar">
          <el-input
            v-model="searchQuery"
            placeholder="搜索帖子标题或内容"
            style="width: 300px"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="filter-controls">
          <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 120px" @change="handleFilter">
            <el-option label="全部" value="" />
            <el-option label="正常" value="0" />
            <el-option label="隐藏" value="1" />
            <el-option label="删除" value="2" />
            <el-option label="封禁" value="3" />
          </el-select>
          
          <el-select v-model="categoryFilter" placeholder="分类筛选" style="width: 140px" @change="handleFilter">
            <el-option label="全部分类" value="" />
            <el-option
              v-for="cat in categoryStore.categories"
              :key="cat.id"
              :label="cat.name"
              :value="cat.id + ''"
            />
          </el-select>
          
          <el-button type="primary" @click="refreshData">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 帖子列表 -->
    <el-card class="table-card">
      <el-table
        :data="posts"
        v-loading="loading"
        stripe
        style="width: 100%"
        :default-sort="{ prop: 'createTime', order: 'descending' }"
      >
        <el-table-column prop="id" label="ID" width="80" sortable />
        
        <el-table-column prop="title" label="标题" width="180" show-overflow-tooltip>
          <template #default="scope">
            <div class="post-title" @click="viewPostDetail(scope.row)">
              {{ scope.row.title }}
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="authorNickname" label="作者" width="120" />
        
        <el-table-column prop="categoryName" label="分类" width="100">
          <template #default="scope">
            <el-tag size="small" type="primary">
              {{ categoryStore.categories.find(cat => cat.id === scope.row.categoryId)?.name || scope.row.categoryName || '未知' }}
            </el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <!-- status: 0-正常 1-隐藏 2-删除 3-封禁 -->
            <el-tag v-if="scope.row.status === 0" type="success" size="small">正常</el-tag>
            <el-tag v-else-if="scope.row.status === 1" type="warning" size="small">隐藏</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="danger" size="small">删除</el-tag>
            <el-tag v-else-if="scope.row.status === 3" type="info" size="small">封禁</el-tag>
            <el-tag v-else type="info" size="small">未知</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="likeCount" label="点赞数" width="90" sortable />
        
        <el-table-column prop="commentCount" label="评论数" width="90" sortable />
        
        <el-table-column prop="createTime" label="发布时间" width="160" sortable>
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="viewPostDetail(scope.row)"
            >
              查看详情
            </el-button>
            <!-- status: 0-正常 1-隐藏 2-删除 3-封禁 -->
            <el-button
              v-if="scope.row.status === 0"
              type="warning"
              size="small"
              @click="togglePostStatus(scope.row, 1)"
            >
              隐藏
            </el-button>
            <el-button
              v-else-if="scope.row.status === 1"
              type="success"
              size="small"
              @click="togglePostStatus(scope.row, 0)"
            >
              显示
            </el-button>
            <el-button
              v-if="scope.row.status !== 2"
              type="danger"
              size="small"
              @click="togglePostStatus(scope.row, 2)"
            >
              删除
            </el-button>
            <el-button
              v-if="scope.row.status !== 3"
              type="info"
              size="small"
              @click="togglePostStatus(scope.row, 3)"
            >
              封禁
            </el-button>
            <el-button
              v-if="scope.row.status === 3"
              type="success"
              size="small"
              @click="togglePostStatus(scope.row, 0)"
            >
              解除封禁
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 帖子详情对话框 -->
    <el-dialog v-model="detailDialogVisible" title="帖子详情" width="800px" top="5vh">
      <div v-if="selectedPost" class="post-detail">
        <div class="detail-header">
          <h2>{{ selectedPost.title }}</h2>
          <div class="post-meta">
            <span>作者：{{ selectedPost.authorNickname }}</span>
            <span>分类：{{ selectedPost.categoryName }}</span>
            <span>发布时间：{{ formatTime(selectedPost.createTime) }}</span>
          </div>
        </div>
        
        <div class="post-stats">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-statistic title="点赞数" :value="selectedPost.likeCount" />
            </el-col>
            <el-col :span="8">
              <el-statistic title="评论数" :value="selectedPost.commentCount" />
            </el-col>
            <el-col :span="8">
              <el-statistic title="浏览数" :value="selectedPost.viewCount || 0" />
            </el-col>
          </el-row>
        </div>
        
        <div class="post-actions">
          <el-button
            @click="router.push(`/forum/${selectedPost.id}`)"
          >
            查看帖子
          </el-button>
          <el-button
            v-if="selectedPost.status === 1"
            type="warning"
            @click="togglePostStatus(selectedPost, 0)"
          >
            隐藏帖子
          </el-button>
          
          <el-button
            v-else-if="selectedPost.status === 0"
            type="success"
            @click="togglePostStatus(selectedPost, 1)"
          >
            显示帖子
          </el-button>
          
          <el-button
            type="danger"
            @click="togglePostStatus(selectedPost, 2)"
          >
            删除帖子
          </el-button>
          
          <el-button
            type="info"
            v-if="selectedPost.status !== 3"
            @click="togglePostStatus(selectedPost, 3)"
          >
            封禁帖子
          </el-button>
          <el-button
            v-if="selectedPost.status === 3"
            type="success"
            @click="togglePostStatus(selectedPost, 0)"
          >
            解除封禁
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { getAllPostsForManager, PostPreviewVO, changePostState } from '@/api/admin'
import { useCategoryStore } from '@/stores/category'
import { useRouter } from 'vue-router'

// 数据定义
const posts = ref<PostPreviewVO[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const router = useRouter()

// 搜索和筛选
const searchQuery = ref('')
const statusFilter = ref('')
const categoryFilter = ref('')

// 对话框
const detailDialogVisible = ref(false)
const selectedPost = ref<PostPreviewVO | null>(null)

const categoryStore = useCategoryStore()

// 获取帖子列表
const fetchPosts = async () => {
  loading.value = true
  try {
    const params: any = {
      page: currentPage.value - 1,
      size: pageSize.value
    }
    if (statusFilter.value !== '') params.status = Number(statusFilter.value)
    if (categoryFilter.value !== '') params.categoryId = Number(categoryFilter.value)
    // TODO: 搜索功能可扩展 params
    const res = await getAllPostsForManager(params)
    console.log("获取帖子列表", res)
    if (res) {
      posts.value = res.records
      total.value = res.total
    } else {
      posts.value = []
      total.value = 0
      ElMessage.error(res.message || '获取帖子列表失败')
    }
  } catch (error) {
    ElMessage.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  // 可扩展为带关键词的接口
  fetchPosts()
}

// 筛选
const handleFilter = () => {
  currentPage.value = 1
  fetchPosts()
}

// 刷新数据
const refreshData = () => {
  fetchPosts()
}

// 分页处理
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
  fetchPosts()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchPosts()
}

// 查看帖子详情
const viewPostDetail = (post: PostPreviewVO) => {
  selectedPost.value = post
  detailDialogVisible.value = true
}

// 切换帖子状态
const togglePostStatus = async (post: PostPreviewVO, newStatus: number) => {
  // status: 0-正常 1-隐藏 2-删除 3-封禁
  let statusText = ''
  switch (newStatus) {
    case 0:
      statusText = '显示'; break;
    case 1:
      statusText = '隐藏'; break;
    case 2:
      statusText = '删除'; break;
    case 3:
      statusText = '封禁'; break;
    default:
      statusText = '未知';
  }
  try {
    await ElMessageBox.confirm(
      `确定要${statusText}帖子《${post.title}》吗？`,
      '确认操作',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    // 调用API更新帖子状态
    const res = await changePostState({ postId: post.id, state: newStatus })
    console.log('切换帖子状态响应:', res)
    if (res === "操作成功") {
      ElMessage.success(`帖子${statusText}成功`)
      if (detailDialogVisible.value) {
        detailDialogVisible.value = false
      }
      fetchPosts()
    } else {
      ElMessage.error(res.message || `帖子${statusText}失败`)
    }
  } catch (error) {
    // 用户取消操作或接口异常
  }
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '未知'
  return new Date(time).toLocaleString()
}

onMounted(() => {
  if (!categoryStore.categories.length) {
    categoryStore.fetchCategories()
  }
  fetchPosts()
})
</script>

<style scoped>
.post-management {
  padding: 24px;
  background: #f5f7fa;
  height: auto;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h1 {
  color: #2c3e50;
  font-size: 2rem;
  margin-bottom: 8px;
  font-weight: 600;
}

.subtitle {
  color: #7f8c8d;
  font-size: 1rem;
  margin: 0;
}

.filter-card {
  margin-bottom: 24px;
  border-radius: 12px;
}

.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  align-items: center;
}

.table-card {
  border-radius: 12px;
  overflow: hidden;
}

.post-title {
  color: #409eff;
  cursor: pointer;
  font-weight: 500;
}

.post-title:hover {
  text-decoration: underline;
}

.pagination-container {
  margin-top: 24px;
  display: flex;
  justify-content: center;
}

.post-detail {
  padding: 16px 0;
}

.detail-header {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.detail-header h2 {
  margin: 0 0 12px 0;
  color: #2c3e50;
  font-size: 1.5rem;
  line-height: 1.4;
}

.post-meta {
  display: flex;
  gap: 16px;
  color: #7f8c8d;
  font-size: 0.9rem;
}

.post-content {
  margin-bottom: 24px;
}

.post-content h4 {
  margin: 0 0 12px 0;
  color: #2c3e50;
  font-size: 1.1rem;
}

.content-preview {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e9ecef;
}

.post-stats {
  margin-bottom: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.post-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 8px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-statistic__number) {
  color: #409eff;
  font-weight: 600;
}
</style>
